package com.jstyle.jclifexd.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.provider.Settings;
import android.support.constraint.ConstraintSet;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.CoordinateConverter;
import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.baoyz.widget.PullRefreshLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jstyle.blesdk.Util.SingleDealData;
import com.jstyle.blesdk.cmdenum.SendCmdState;
import com.jstyle.blesdk.constant.DeviceKey;
import com.jstyle.blesdk.model.DeviceBean;
import com.jstyle.blesdk.model.GetData;
import com.jstyle.jclifexd.NetWork.NetWorkUtil;
import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.adapter.HistoryDateAdapter;
import com.jstyle.jclifexd.adapter.RecyclerViewBaseAdapter;
import com.jstyle.jclifexd.adapter.TrackRecordAdapter;
import com.jstyle.jclifexd.app.MyApplication;
import com.jstyle.jclifexd.ble.BleManager;
import com.jstyle.jclifexd.daoManager.GpsDataDaoManager;
import com.jstyle.jclifexd.daoManager.PathRecordDaoManager;
import com.jstyle.jclifexd.daoManager.StepDetailDataDaoManager;
import com.jstyle.jclifexd.daoManager.UserInfoDaoManager;
import com.jstyle.jclifexd.minterface.OnScrollToListener;

import com.jstyle.jclifexd.model.Device166806x;
import com.jstyle.jclifexd.model.Device1810;
import com.jstyle.jclifexd.model.Device181003;
import com.jstyle.jclifexd.model.Device1810xa;
import com.jstyle.jclifexd.model.GpsData;
import com.jstyle.jclifexd.model.ItemData;

import com.jstyle.jclifexd.model.JstyleDevice;
import com.jstyle.jclifexd.model.PathRecord;
import com.jstyle.jclifexd.model.PathRecorderror;
import com.jstyle.jclifexd.model.UploadData;
import com.jstyle.jclifexd.model.UploadGpsData;
import com.jstyle.jclifexd.model.UploadGpsDataError;
import com.jstyle.jclifexd.utils.BleSendSingleton;
import com.jstyle.jclifexd.utils.CoordinateUtil;
import com.jstyle.jclifexd.utils.DateUtil;
import com.jstyle.jclifexd.utils.NetWorkConast;
import com.jstyle.jclifexd.utils.PermissionsUtil;
import com.jstyle.jclifexd.utils.SchedulersTransformer;
import com.jstyle.jclifexd.utils.ScreenUtils;
import com.jstyle.jclifexd.utils.SharedPreferenceUtils;
import com.jstyle.jclifexd.utils.UploadUtils;
import com.jstyle.jclifexd.utils.Utils;

import org.json.JSONArray;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class ExerciseRecordListActivity extends BaseActivity implements RecyclerViewBaseAdapter.OnItemClickListener, PullRefreshLayout.OnRefreshListener,/* AMapLocationListener,*/ GeocodeSearch.OnGeocodeSearchListener {

    @BindView(R.id.RecyclerView_exercise_Record)
    RecyclerView RecyclerViewExerciseRecord;
    @BindView(R.id.bt_goal_back)
    Button btGoalBack;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_share)
    ImageView ivShare;
    @BindView(R.id.tv_track_totalTime)
    TextView tvTrackTotalTime;
    @BindView(R.id.tv_refresh_tips)
    TextView tvRefreshTips;
    @BindView(R.id.iv_refresh_tips)
    ImageView ivRefreshTips;
    @BindView(R.id.rl_refresh_tips)
    RelativeLayout rlRefreshTips;
   /* @BindView(R.id.SwipeRefreshLayout)
    PullRefreshLayout SwipeRefreshLayout;*/
    public static boolean needAutoSyc = true;
    private static final String TAG = "ExerciseRecordListActiv";


    private TrackRecordAdapter myAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exercise_record);
        ButterKnife.bind(this);
        ivShare.setImageDrawable(getResources().getDrawable(R.drawable.data_health));
        if (MyApplication.getJstyleDevice() instanceof Device1810 || MyApplication.getJstyleDevice() instanceof Device181003||MyApplication.getJstyleDevice() instanceof Device166806x||MyApplication.getJstyleDevice() instanceof Device1810xa) {
            tvRefreshTips.setVisibility(View.INVISIBLE);
            ivRefreshTips.setVisibility(View.INVISIBLE);
        }


        init();
    }



    private void init() {
        btGoalBack.setText(R.string.Workout_History);
        ScreenUtils.setTitleTypeface(btGoalBack);
        final List<PathRecord> pathRecordList = PathRecordDaoManager.getAllPathRecord();
        int totalTime = 0;
        Map<String, List<PathRecord>> mapPathRecord = new HashMap<>();
        for (PathRecord pathRecord : pathRecordList) {
            String date = pathRecord.getMDate();
            String month = date.substring(0, 5);
            List<PathRecord> list = mapPathRecord.get(month);
            if (list == null) {
                list = new ArrayList<>();
                mapPathRecord.put(month, list);
            }
            list.add(pathRecord);
            totalTime += Integer.parseInt(pathRecord.getMDuration());
        }
        Log.i(TAG, "init: path finish ");
        ScreenUtils.setTitleTypeface(tvTrackTotalTime);
        tvTrackTotalTime.setText(DateUtil.getSportTime(totalTime));
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        RecyclerViewExerciseRecord.setLayoutManager(linearLayoutManager);
        RecyclerViewExerciseRecord.getItemAnimator().setAddDuration(100);
        RecyclerViewExerciseRecord.getItemAnimator().setRemoveDuration(100);
        RecyclerViewExerciseRecord.getItemAnimator().setMoveDuration(200);
        RecyclerViewExerciseRecord.getItemAnimator().setChangeDuration(100);
        myAdapter = new TrackRecordAdapter(this);
        RecyclerViewExerciseRecord.setAdapter(myAdapter);
        myAdapter.setOnScrollToListener(new OnScrollToListener() {

            @Override
            public void scrollTo(int position) {
                RecyclerViewExerciseRecord.smoothScrollToPosition(position);
            }
        });
        initDatas(mapPathRecord);
        myAdapter.setMapClickListener(new TrackRecordAdapter.onMapItemClickListener() {
            @Override
            public void onClick(PathRecord pathRecord, LatLng latLng) {
                int mode = pathRecord.getExerciseMode();
                Log.i(TAG, "onClick: " + mode);
                if (mode == 5 || mode == 6 || mode == 7 || mode == 10) return;
                startHistoryActivity(pathRecord, latLng);
            }
        });

    }

    private void initDatas(Map<String, List<PathRecord>> map) {
        List<ItemData> list = new ArrayList<>();
        Log.i(TAG, "initDatas: path2");
        for (Map.Entry<String, List<PathRecord>> entry : map.entrySet()) {
            ItemData itemData = new ItemData();
            itemData.setUuid(UUID
                    .randomUUID().toString());
            itemData.setmDate(entry.getKey());
            itemData.setPathRecordList(entry.getValue());
            list.add(itemData);
        }

        if (list.size() == 0) return;
        Collections.sort(list);
        Log.i(TAG, "initDatas: path2 finish ");
        ItemData itemData = list.get(0);
        itemData.setExpand(true);
        List<ItemData> children = myAdapter.getChildrenByPath(itemData.getPathRecordList(), itemData.getTreeDepth());
        list.addAll(1, children);
        itemData.setChildren(children);
        myAdapter.addAll(list, 0);
    }

    private void startHistoryActivity(final PathRecord pathRecord, final LatLng latLng) {
        PermissionsUtil.requestPermissions(this, new PermissionsUtil.PermissionListener() {
            @Override
            public void granted(String name) {
                if (Utils.isFastClicktwo()) {
                    return;
                }
                if (Utils.checkNetWork(ExerciseRecordListActivity.this)) {
                    startRecordHistoryActivity(latLng, pathRecord);
                } else {
                    showToast(ExerciseRecordListActivity.this.getString(R.string.Network_not_availa));
                }
            }

            @Override
            public void NeverAskAgain() {

            }

            @Override
            public void disallow(String name) {

            }
        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    }

    String mDate;
    Class historyActivity;
    LatLng myLatLng;

    private void startRecordHistoryActivity(LatLng latLng, PathRecord pathRecord) {
        if (!PermissionsUtil.isLocServiceEnable(this)) {
            showEnableGps();
            return;
        }
        historyActivity = ExerciseHistoryGoogleActivity.class;
        mDate = pathRecord.getMDate();
        if (latLng != null) {
            myLatLng = latLng;
            GeocodeSearch geocodeSearch = new GeocodeSearch(ExerciseRecordListActivity.this);
            geocodeSearch.setOnGeocodeSearchListener(ExerciseRecordListActivity.this);
            LatLonPoint latLonPoint = new LatLonPoint(latLng.latitude, latLng.longitude);
            RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);
            geocodeSearch.getFromLocationAsyn(query);
        } else {
            if (Utils.isZh(ExerciseRecordListActivity.this)) {
                historyActivity = ExerciseHistoryActivity.class;
                toHistoryActivity(true);
            } else {
                historyActivity = ExerciseHistoryGoogleActivity.class;
                toHistoryActivity(true);
            }
        }


    }

    @OnClick({R.id.iv_back, R.id.iv_share})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_share:
                Intent intent = new Intent(this, GrowthMianRecordActivity.class);
                intent.putExtra("my", "my");//my代表自己查看的数据
                intent.putExtra("uid", NetWorkUtil.getUserId());
                intent.putExtra("uname", UserInfoDaoManager.getUserByUid(NetWorkUtil.getUserId()).getName());
                startActivity(intent);
                break;
        }
    }

    boolean isUpload;

    @Override
    public void onItemClick(int position) {

    }

    List<UploadGpsData.DataTotalBean.DataDetailBean> listHealth = new ArrayList<>();
    List<UploadData.DataTotalBean> dataListSportType = new ArrayList<>();

    @Override
    public void dataCallback(DeviceBean deviceBean, SendCmdState sendCmdState) {
        super.dataCallback(deviceBean, sendCmdState);
    }






    @Override
    public void onRefresh() {
        ivRefreshTips.clearAnimation();
        rlRefreshTips.setVisibility(View.INVISIBLE);
        if (!BleManager.getInstance().isConnected()) {
            //SwipeRefreshLayout.setRefreshing(false);
            ScreenUtils.showSetSuccessFul(tvTrackTotalTime, getString(R.string.Bluetooth_Disconnected));
        } else {
            listHealth.clear();
            dataListSportType.clear();
            //if(!BleSendSingleton.getInstance().isSync()) BleSendSingleton.getInstance().getExerciseData();
        }
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /*    @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            Log.i(TAG, "onLocationChanged: " + aMapLocation.getLatitude() + " " + aMapLocation.getLongitude());
            isMainLand = "中国".equals(aMapLocation.getCountry()) && !"1852".equals((aMapLocation.getCityCode()));
            //LocationChanged = !TextUtils.isEmpty(aMapLocation.getCountry());
            LocationChanged=true;
            Log.i(TAG, "onLocationChanged: country " + aMapLocation.getCountry() + " LocationChanged: " + LocationChanged);
        }*/
    private int GPS_REQUEST_CODE = 330;

    private void showEnableGps() {
        new AlertDialog.Builder(this, R.style.appalertdialog).setTitle(R.string.open_gps_setting_title)
                .setMessage(R.string.open_gps_setting_content)
                //  取消选项
                .setNegativeButton(getString(R.string.access_no), null)
                //  确认选项
                .setPositiveButton(getString(R.string.access_now), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //跳转到手机原生设置页面
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivityForResult(intent, GPS_REQUEST_CODE);
                    }
                })
                .setCancelable(false)
                .show();
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        boolean isTransFormer = false;
        if (i == 1000) {
            if (null != regeocodeResult.getRegeocodeAddress() && regeocodeResult.getRegeocodeAddress().getCountry().equals("中国")) {
                if ("1852".equals(regeocodeResult.getRegeocodeAddress().getCityCode())) {//香港澳门
                    historyActivity = ExerciseHistoryGoogleActivity.class;
                    isTransFormer = false;//香港澳门需要偏纠
                } else {
                    historyActivity = ExerciseHistoryActivity.class;
                    isTransFormer = true;
                }
            } else {
                historyActivity = ExerciseHistoryGoogleActivity.class;
                isTransFormer = true;//不在香港澳门，或者中国就不需要偏纠
            }
        } else {
            if (CoordinateUtil.outOfChina(myLatLng.latitude, myLatLng.longitude)) {
                historyActivity = ExerciseHistoryGoogleActivity.class;
                isTransFormer = true;
            } else {
                if (Utils.isTAiwan(myLatLng) || Utils.isXianggan(myLatLng)) {
                    historyActivity = ExerciseHistoryGoogleActivity.class;
                    isTransFormer = false;//香港澳门需要偏纠
                } else {
                    historyActivity = ExerciseHistoryActivity.class;
                    isTransFormer = true;
                }
            }
        }
        toHistoryActivity(isTransFormer);

    }

    private void toHistoryActivity(boolean isTransFormer) {
        Intent intent = new Intent(this, historyActivity);
        intent.putExtra(ExerciseHistoryActivity.pathRecordDate, mDate);
        intent.putExtra("isTransFormer", isTransFormer);
        startActivity(intent);
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }

    @Override
    protected void onDisconnect() {
        super.onDisconnect();
       // SwipeRefreshLayout.setRefreshing(false);
       ScreenUtils.showSetSuccessFul(RecyclerViewExerciseRecord, getString(R.string.disonnected));
    }

    @Override
    protected void syncGpsDataFinished() {
        super.syncGpsDataFinished();
        disMissProgressDialog();
       // SwipeRefreshLayout.setRefreshing(false);
        init();
    }
}
